package com.itggm.controller;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.itggm.Result.ResponseResult;
import com.itggm.dto.CoursePageDTO;
import com.itggm.exception.BusinessException;
import com.itggm.pojo.Course;
import com.itggm.service.CourseService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author: ggm
 * @data 2024年12月27日 20:08
 */
@Slf4j
@RestController
@RequestMapping("/course")
public class CourseController {
    @Resource
    private CourseService courseService;
    @Resource
    private RedisTemplate redisTemplate;

     /**
      * @Author: ggm
      * @date:  2024/12/27
      * 获取课程列表
      */
     @RequestMapping("/list")
     public ResponseResult courseList(){
         log.info("课程列表");
         //先从redis中查询
         List<Course> redisCourseList = (List<Course>) redisTemplate.opsForValue().get("_course");
         if(ObjectUtils.isEmpty(redisCourseList)){
             List<Course> courseList = courseService.list();
             //将部门数据缓存到redis中去
             redisTemplate.opsForValue().set("_course",courseList);
             return ResponseResult.success().data("courseList",courseList);
         }
         return ResponseResult.success().data("courseList",redisCourseList);
     }
      /**
       * @Author: ggm
       * @date:  2024/12/28
       * 分页查询
       */
      @PostMapping("/page")
      public ResponseResult coursePage(@RequestBody CoursePageDTO coursePageDTO){
          log.info( "分页查询{}", coursePageDTO);
          return courseService.coursePage(coursePageDTO);

      }
       /**
        * @Author: ggm
        * @date:  2024/12/30
        * 添加或修改课程数据
        */
       @PostMapping("/addOrUpdate")
       public ResponseResult addOrUpdateCourse(@RequestBody Course course){
           log.info("添加或修改课程数据{}",course);
           try {
               courseService.saveOrUpdate(course);
               return  ResponseResult.success();
           }catch (Exception e){
               throw  new BusinessException("课程名重复");
           }

       }
        /**
         * @Author: ggm
         * @date:  2024/12/30
         * 修改课程状态
         */
        @GetMapping("/updateStatus/{id}/{status}")
        public ResponseResult updateCourseStatus(@PathVariable("id") Integer id,@PathVariable("status") Integer status){
            log.info("修改课程状态{},{}",id,status);
            return courseService.updateCourseStatus(id,status);
        }
         /**
          * @Author: ggm
          * @date:  2024/12/30
          * 删除课程信息
          */
         @DeleteMapping("delete/{id}")
         public ResponseResult deleteCourse(@PathVariable("id") Integer id){
             return courseService.deleteCourse(id);
         }


}
